package io.itit.ecp.admin.provide.action.controller.miniprogram;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.provide.action.req.HourElectricityPriceQueryReq;
import io.itit.ecp.admin.provide.action.resp.HourElectricityPriceResp;
import io.itit.ecp.admin.server.entity.HourElectricityPriceEntity;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.Objects;

/**
 * 分时电价控制类
 */
@Api(tags = "分时电价管理")
@RestController
@RequestMapping("/mini/hourElectricityPrice")
public class MiniHourElectricityPriceController {

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    public ResultResp<IPage<HourElectricityPriceResp>> queryPage(@RequestBody @Validated(IQueryPage.class) HourElectricityPriceQueryReq req) {
        Page<HourElectricityPriceResp> page = buildQW(req).joinPage(PageUtils.getPage(req, HourElectricityPriceResp.class), HourElectricityPriceResp.class);
        return ResultResp.success(page);
    }

    private static JoinLambdaWrapper<HourElectricityPriceEntity> buildQW(HourElectricityPriceQueryReq req) {
        LocalDate start = null;
        LocalDate end = null;
        if (ArrayUtils.isNotEmpty(req.getTimeRange()) && req.getTimeRange().length == 2) {
            start = LocalDate.parse(req.getTimeRange()[0]);
            end = LocalDate.parse(req.getTimeRange()[1]);
        }
        return Joins.of(HourElectricityPriceEntity.class)
                .eq(StringUtils.hasLength(req.getSceneProjectId()), HourElectricityPriceEntity::getSceneProjectId, req.getSceneProjectId())
                .eq(StringUtils.hasLength(req.getPeakValleyType()), HourElectricityPriceEntity::getPeakValleyType, req.getPeakValleyType())
                .ge(Objects.nonNull(start), HourElectricityPriceEntity::getStartDate, start)
                .le(Objects.nonNull(end), HourElectricityPriceEntity::getEndDate, end)
                .orderByDesc(StringUtils.hasLength(req.getSortColumn()), HourElectricityPriceEntity::getCreateTm);
    }
}
